package com.example.finalhomework.musicplayer

import android.media.MediaPlayer
import android.net.Uri
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.navigation.NavHostController
import com.example.finalhomework.R
import java.io.File

@Composable
fun MusicPlayerScreen(navController: NavHostController) {
    val context = LocalContext.current
    // 获取 MusicPlayerViewModel 实例
    val viewModel: MusicPlayerViewModel = ViewModelProvider(context as ViewModelStoreOwner).get(MusicPlayerViewModel::class.java)

    // 使用 LaunchedEffect 在组合项启动时执行一次性操作
    LaunchedEffect(Unit) {
        viewModel.loadMusicFiles(context) // 加载音乐文件
        if (viewModel.isPlaying) { // 如果正在播放
            if (viewModel.mediaPlayer == null) { // 如果 mediaPlayer 为空
                // 创建新的 MediaPlayer 实例并设置数据源
                viewModel.mediaPlayer = MediaPlayer.create(context, Uri.parse(viewModel.trackList[viewModel.currentTrackIndex]))
                // 将 MediaPlayer 的进度设置为上次保存的进度
                viewModel.mediaPlayer?.seekTo((viewModel.progress * (viewModel.mediaPlayer?.duration ?: 0)).toInt())
                // 设置播放完成监听器，播放下一首
                viewModel.mediaPlayer?.setOnCompletionListener {
                    viewModel.playNextTrack()
                }
                viewModel.mediaPlayer?.start() // 开始播放
            }
            viewModel.startUpdatingProgress() // 开始更新进度
        }
        Log.d("MusicPlayerScreen", "LaunchedEffect executed")
    }

    // 获取当前音乐信息
    val (currentMusicName, progress) = viewModel.getCurrentMusicInfo()
    Log.d("MusicPlayerScreen", "Loaded music: $currentMusicName, Progress: $progress")

    // 布局容器，填充整个屏幕
    Box(
        modifier = Modifier
            .fillMaxSize(),
        contentAlignment = Alignment.CenterEnd
    ) {
        // 显示背景图片
        Image(
            painter = painterResource(id = R.drawable.background9),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxHeight().align(Alignment.CenterEnd)
        )
        // 垂直排列的列容器
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 显示当前音乐名称
            Text(text = "Current music: ${if (currentMusicName.isNotEmpty()) currentMusicName else viewModel.currentMusicName}", fontSize = 20.sp)
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 播放进度滑块
            Slider(
                value = viewModel.progress,
                onValueChange = { newProgress ->
                    viewModel.progress = newProgress // 更新进度
                },
                onValueChangeFinished = {
                    viewModel.mediaPlayer?.let {
                        val newPosition = (viewModel.progress * it.duration).toInt()
                        it.seekTo(newPosition) // 设置新的播放位置
                        Log.d("MusicPlayerScreen", "Seek to: $newPosition")
                    }
                },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 播放按钮
            Button(onClick = {
                if (viewModel.trackList.isNotEmpty()) {
                    if (viewModel.mediaPlayer == null) {
                        // 创建新的 MediaPlayer 实例并设置数据源
                        viewModel.mediaPlayer = MediaPlayer.create(context, Uri.parse(viewModel.trackList[viewModel.currentTrackIndex]))
                        // 设置播放完成监听器，播放下一首
                        viewModel.mediaPlayer?.setOnCompletionListener {
                            viewModel.playNextTrack()
                        }
                    }
                    viewModel.mediaPlayer?.start() // 开始播放
                    viewModel.isPlaying = true // 设置播放状态为 true
                    viewModel.currentMusicName = File(viewModel.trackList[viewModel.currentTrackIndex]).name // 更新当前播放的音乐文件名
                    Log.d("MusicPlayerScreen", "Playing music: ${viewModel.currentMusicName}")
                    viewModel.startUpdatingProgress() // 开始更新进度
                    viewModel.showNotification(viewModel.currentMusicName) // 显示通知
                }
            },
                modifier = Modifier.width(90.dp)
            ) {
                Text(text = "Play")
            }
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 暂停按钮
            Button(onClick = {
                viewModel.mediaPlayer?.pause() // 暂停播放
                viewModel.pauseMusic() // 调用暂停音乐方法
                viewModel.isPlaying = false // 设置播放状态为 false
                Log.d("MusicPlayerScreen", "Paused music: ${viewModel.currentMusicName}")
                viewModel.stopUpdatingProgress() // 停止更新进度
            },
                modifier = Modifier.width(90.dp)
            ) {
                Text(text = "Pause")
            }
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 停止按钮
            Button(onClick = {
                viewModel.mediaPlayer?.stop() // 停止播放
                viewModel.mediaPlayer?.reset() // 重置 MediaPlayer
                viewModel.mediaPlayer = null // 将 mediaPlayer 置为 null
                viewModel.releaseMediaPlayer() // 释放媒体播放器资源
                viewModel.stopMusic() // 调用停止音乐方法
                viewModel.isPlaying = false // 设置播放状态为 false
                Log.d("MusicPlayerScreen", "Stopped music: ${viewModel.currentMusicName}")
                viewModel.stopUpdatingProgress() // 停止更新进度
            },
                modifier = Modifier.width(90.dp)
            ) {
                Text(text = "Stop")
            }
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 下一首按钮
            Button(onClick = {
                viewModel.playNextTrack() // 播放下一首音乐
                Log.d("MusicPlayerScreen", "Next music: ${viewModel.currentMusicName}")
            },
                modifier = Modifier.width(90.dp)
            ) {
                Text(text = "Next")
            }
            Spacer(modifier = Modifier.height(16.dp)) // 间隔
            // 上一首按钮
            Button(onClick = {
                if (viewModel.trackList.isNotEmpty()) {
                    viewModel.currentTrackIndex = if (viewModel.currentTrackIndex - 1 < 0) viewModel.trackList.size - 1 else viewModel.currentTrackIndex - 1
                    viewModel.mediaPlayer?.release() // 释放现有的 MediaPlayer
                    // 创建 MediaPlayer 实例并设置数据源
                    viewModel.mediaPlayer = MediaPlayer.create(context, Uri.parse(viewModel.trackList[viewModel.currentTrackIndex]))
                    // 设置播放完成监听器，播放下一首
                    viewModel.mediaPlayer?.setOnCompletionListener {
                        viewModel.playNextTrack()
                    }
                    if (viewModel.isPlaying) {
                        viewModel.mediaPlayer?.start() // 开始播放
                    }
                    viewModel.currentTrackName = viewModel.trackList[viewModel.currentTrackIndex] // 更新当前播放的音乐名称
                    viewModel.currentMusicName = File(viewModel.trackList[viewModel.currentTrackIndex]).name // 更新当前播放的音乐文件名
                    Log.d("MusicPlayerScreen", "Previous music: ${viewModel.currentMusicName}")
                }
            },
                modifier = Modifier.width(90.dp)
            ) {
                Text(text = "Prev")
            }
        }
    }
}